﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace GameFrameWork
{
    public class ReqAwaiter : IAwaiter<ReqAwaiter, DownloadHandler>, IDisposable
    {
        public bool IsCompleted { get; set; }
        public string Url { get; private set; }

        public UnityWebRequest req { get; private set; }

        public ReqAwaiter(string url)
        {
            Url = url;
        }

        public ReqAwaiter GetAwaiter()
        {
            return this;
        }

        public DownloadHandler GetResult()
        {
            return req?.downloadHandler;
        }

        public void OnCompleted(Action continuation)
        {
            if (req != null)
                req.Dispose();
            req = UnityWebRequest.Get(Url);
            var op = req.SendWebRequest();
            op.completed += (pp) =>
            {
                continuation?.Invoke();
            };
        }
        public void Dispose()
        {
            req?.Dispose();
        }
    }
}


